package com.GlobalPaint.app.ui.Register;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.GlobalPaint.app.Base.BaseActivity;
import com.GlobalPaint.app.R;
import com.GlobalPaint.app.bean.LogBean;
import com.GlobalPaint.app.bean.ReturnStatusResultEntity;
import com.GlobalPaint.app.bean.codeBean;
import com.GlobalPaint.app.ui.HTML.FuWuHTML;
import com.GlobalPaint.app.utils.AppManager;
import com.GlobalPaint.app.utils.CommUtility;
import com.GlobalPaint.app.utils.Constants;
import com.GlobalPaint.app.utils.DataManager;
import com.blankj.utilcode.utils.RegexUtils;
import com.blankj.utilcode.utils.SPUtils;
import com.blankj.utilcode.utils.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.GlobalPaint.app.R.id.tv_getcode;

public class Register extends BaseActivity {

    private final int CMD_GET_VALIDATE = 0x0002;
    private final int CMD_GET_CODE = 0x0001;
    @BindView(R.id.iv_goback)
    ImageView ivGoback;
    @BindView(R.id.tv_common_center)
    TextView tvCommonCenter;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(tv_getcode)
    TextView tvGetcode;
    @BindView(R.id.bt_submit)
    Button btSubmit;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.tv_fu)
    TextView tvFu;
    @BindView(R.id.et_newpassword)
    EditText etNewpassword;
    @BindView(R.id.et_password)
    EditText etPassword;
    private String checkbox1 = "未选中";
    private codeBean codebean;
    private Pattern pattern;
    private boolean matches;
    private LogBean logBean;
    private SPUtils spUtils;
    private Handler mhandler = new Handler() {
        public void handleMessage(Message message) {
            switch (message.what) {
                case CMD_GET_CODE:
                    String url = Constants.JASON_SERVICE_URL + "user/sendSms?type=0&phone=" + String.valueOf(etPhone.getText());
                    DataManager.getInst().getHttpRequestJsonClass(url, "dd", codeBean.class, new DataManager.Callback() {
                        @Override
                        public void onSuccess(Object o) {
                            codebean = (codeBean) o;
                            if (codebean.getStatus() == 1) {
                                runnable.run();
                            } else {
                                Toast.makeText(Register.this, codebean.getMsg(), Toast.LENGTH_LONG).show();
                            }

                        }

                        @Override
                        public void onFailure(ReturnStatusResultEntity error) {
                            Toast.makeText(Register.this, "获取验证码失败请稍后再试", Toast.LENGTH_LONG).show();
                        }
                    });

                    break;
                case CMD_GET_VALIDATE:
                    String url1 = Constants.JASON_SERVICE_URL + "user/register?fUsername="
                            + String.valueOf(etPhone.getText()) + "&verificationCode=" + String.valueOf(etCode.getText())
                            +"&fPassword="+etPassword.getText().toString();
                    DataManager.getInst().getHttpRequestJsonClass(url1, "dd", LogBean.class, new DataManager.Callback() {
                        @Override
                        public void onSuccess(Object o) {
                            logBean = (LogBean) o;
                            if (logBean.getStatus() == 1) {
                                finish();
                            } else {
                                Toast.makeText(Register.this, logBean.getMsg(), Toast.LENGTH_LONG).show();
                            }

                        }

                        @Override
                        public void onFailure(ReturnStatusResultEntity error) {
                            //Toast.makeText(Register.this,"获取验证码失败请稍后再试",Toast.LENGTH_LONG).show();
                        }
                    });
                    break;
            }
        }
    };
    int recLen = 0;
    int total = 60;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            recLen++;
            int remain = total - recLen;
            if (remain == 0) {
                recLen = 0;
                tvGetcode.setText("重新发送");
                tvGetcode.setEnabled(true);
                return;
            } else {
                tvGetcode.setEnabled(false);
                String display = String.valueOf(remain) + "秒后重发";
                tvGetcode.setText(display);
            }
            handler.postDelayed(this, 1000);
        }
    };
    private TextView tv_common_center;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        spUtils = new SPUtils(DataManager.context, "login");
        initView();
    }

    private void initView() {
        tvCommonCenter.setText("注册");
        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    checkbox1 = "选中";
                } else {
                    checkbox1 = "未选中";
                }
            }
        });
    }

    private void getSubmit() {
        //检查
        String phone = String.valueOf(etPhone.getText());
        if (TextUtils.isEmpty(phone)) {
            CommUtility.ShowMsgShort(this, "请输入手机号");
            return;
        } else {
            if (!RegexUtils.isMobileSimple(phone)) {
                CommUtility.ShowMsgShort(this, "请输入正确手机号");
                return;
            }

            String validateCode = String.valueOf(etCode.getText());
            if (TextUtils.isEmpty(validateCode)) {
                CommUtility.ShowMsgShort(this, "请获取验证码");
                return;
            } else if (validateCode.length() == 6) {
                Pattern pattern = Pattern.compile("[0-9]*");
                Matcher isNum = pattern.matcher(validateCode);
                if (!isNum.matches()) {
                    CommUtility.ShowMsgShort(this, "验证码为6位数字");
                    return;
                }
            } else {
                CommUtility.ShowMsgShort(this, "验证码为6位数字");
                return;
            }
            String newpassweod=etNewpassword.getText().toString();
            if(TextUtils.isEmpty(newpassweod)){
                CommUtility.ShowMsgShort(this, "请输入密码");
                return;
            }else {
                if (newpassweod.length() < 6 || newpassweod.length() > 20) {
                    CommUtility.ShowMsgShort(this, "请输入6-20位密码");
                    return;
                }
            }
            String password=etPassword.getText().toString();
            if(TextUtils.isEmpty(password)){
                CommUtility.ShowMsgShort(this, "请确认密码");
                return;
            }else {
                if (password.length() < 6 || password.length() > 20) {
                    CommUtility.ShowMsgShort(this, "请输入6-20位密码");
                    return;
                }
            }
            if(!password.equals(newpassweod)){
                CommUtility.ShowMsgShort(this, "两次输入的密码不同，请重新输入");
                return;
            }
            mhandler.sendEmptyMessage(CMD_GET_VALIDATE);

        }
    }

    @OnClick({R.id.iv_goback, tv_getcode, R.id.bt_submit, R.id.tv_fu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_goback:
                finish();
                break;
            case tv_getcode:
                //检查

                String phone = String.valueOf(etPhone.getText());
                String regexPhone = "1[34578]\\d{9}";
                pattern = Pattern.compile(regexPhone);
                matches = pattern.matcher(phone).matches();
                if (StringUtils.isEmpty(phone)) {
                    CommUtility.ShowMsgShort(this, "手机号码不能为空");
                    return;
                }
                if (!matches) {
                    CommUtility.ShowMsgShort(this, "您输入的手机号码有误");
                    return;
                }
                if (!RegexUtils.isMobileSimple(phone)) {
                    CommUtility.ShowMsgShort(this, "请填写手机号");
                    return;
                }

                mhandler.sendEmptyMessage(CMD_GET_CODE);
                break;
            case R.id.bt_submit:
                if (checkbox1.equals("未选中")) {
                    Toast.makeText(Register.this, "请勾选“服务条款”", Toast.LENGTH_LONG).show();
                    return;
                }

                getSubmit();

                break;
            case R.id.tv_fu:
                Intent intent = new Intent(Register.this, FuWuHTML.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (CommUtility.isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
    }

}
